#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
flask 配置
Attributes:
    __version__ (str): "0.0.1"
    __copyright__ (str): "Copyright (C) 2025 z"
    __license__ (str): "MIT"
    __author__ (str): "Z"
"""

import subprocess

from flask import send_file
from apscheduler.schedulers.background import BackgroundScheduler

from router.flask_app import FlaskApp
from router import hook_map, register
from config.system import IS_INSPECTION

app = FlaskApp(
    import_name=__name__,
    static_folder="/",
    static_url_path="/"
)


@app.get('/')
def index():
    """静态首页
    :return:
    """
    return send_file('webhook/index.html')


def init_app(flask_app):
    """初始化app
    :param flask_app:
    :return:
    """
    # 注册路由
    register.register_app_routers(flask_app, hook_map.routes)
    # 全局异常捕获,也相当于一个视图函数
    # flask_app.register_error_handler(Exception, handler.error_handler)


if IS_INSPECTION:
    # 创建调度器
    scheduler = BackgroundScheduler()

    def run_second(test_dir):
        try:
            subprocess.run(['python', test_dir], check=True)
        except subprocess.CalledProcessError as e:
            print(f"测试运行失败: {e}")
    # 添加定时任务
    scheduler.add_job(func=run_second, args=['inspection/alertmanager.py'], trigger='interval', minutes=1)

    def run_pytest_minute(test_dir):
        """运行指定目录的pytest测试"""
        try:
            subprocess.run(['pytest', test_dir], check=True)
        except subprocess.CalledProcessError as e:
            print(f"测试运行失败: {e}")
    scheduler.add_job(func=run_pytest_minute, args=['inspection/minute'], trigger='interval', minutes=1)

    def run_pytest_day(test_dir):
        """运行指定目录的pytest测试"""
        try:
            subprocess.run(['pytest', '-W', 'ignore', test_dir], check=True)
        except subprocess.CalledProcessError as e:
            print(f"测试运行失败: {e}")
    scheduler.add_job(func=run_pytest_day, args=['inspection/day'], trigger='cron', hour=13, minute=30)

    def run_pytest_report(test_dir):
        """运行指定目录的pytest测试"""
        try:
            subprocess.run(['pytest', '-W', 'ignore', test_dir], check=True)
        except subprocess.CalledProcessError as e:
            print(f"测试运行失败: {e}")
    scheduler.add_job(func=run_pytest_report, args=['inspection/report.py'], trigger='cron', hour=13, minute=30)

    # 启动调度器
    scheduler.start()

init_app(app)
